// Bristleback plugin - Copyright (c) 2010 bristleback.googlecode.com
// ---------------------------------------------------------------------------
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation; either version 3 of the License, or (at your
// option) any later version.
// This library is distributed in the hope that it will be useful,
// but without any warranty; without even the implied warranty of merchantability
// or fitness for a particular purpose.
// You should have received a copy of the GNU Lesser General Public License along
// with this program; if not, see <http://www.gnu.org/licenses/lgpl.html>.
// ---------------------------------------------------------------------------
package pl.bristleback.server.bristle.messages;

import org.apache.log4j.Logger;
import org.jwebsocket.api.WebSocketConnector;
import org.jwebsocket.token.Token;
import pl.bristleback.server.bristle.rights.ConnectorRightsUtil;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * This implementation iterates from all connectors and checks whether connector contains every right
 * given in array as parameter.
 * todo-wojtek make possible to pass list and array as parameter, currently only array is possible.
 * <p/>
 * Created on: 2010-09-27 16:13:56 <br/>
 *
 * @author Wojciech Niemiec
 */
public class RightsCheckingMessageBroadcaster extends AbstractMessageSender<String[]> {
  private static Logger log = Logger.getLogger(RightsCheckingMessageBroadcaster.class.getName());

  public static final String SENDER_NAME = "rightsCheckingBroadcaster";

  public void sendMessage(Token token, String... requiredRights) {
    Collection<WebSocketConnector> connectors = getServer().getAllConnectors().values();
    List<WebSocketConnector> recipients = new LinkedList<WebSocketConnector>();
    for (WebSocketConnector connector : connectors) {
      if (ConnectorRightsUtil.hasRights(connector, requiredRights)) {
        recipients.add(connector);
      }
    }
    if (!recipients.isEmpty()) {
      WebSocketMessage message = new WebSocketMessage(token, recipients);
      getMessageDispatcher().addMessage(message);
    }
  }
}
